package jrmob.yonyou.com.commonlib.baseui.base;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jrmob.yonyou.com.commonlib.AppManager;
import jrmob.yonyou.com.commonlib.R;
import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseManager.DBManager;
import jrmob.yonyou.com.commonlib.login.activity.LoginBaseActivity_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;
import jrmob.yonyou.com.commonlib.login.bean.UserInfoLRY;
import jrmob.yonyou.com.commonlib.login.bean.UserInfo_lib;


/**
 * activity基类
 * Created by zhangguang on 16/10/22.
 */

public abstract class BaseActivityMob_lib extends AppCompatActivity implements View.OnClickListener {


    //这个一般不要重新赋值
    protected static SharedPreferences mShare;
    protected BitmapUtils bitmapUtils;
    protected BaseActivityMob_lib mActivity;
    protected FragmentManager fragmentManager;
    protected FragmentTransaction beginTransaction;
    public DBManager mgr;
    public Toast mToast;
    private List<String> permissionList;
    /**
     * 全屏界面改变此值为任意其他值
     */
    public int tempStatus = -1;

    public String appDownloadPath; // app安装路径

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getInstance(this).addActivity(this);

        //为变量赋值
        assignmentForParameter();
        initPermission();
    }

    // 获得download路径
    public String getDownloadPath() {
        return appDownloadPath;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tempStatus == -1) {
            //StatusBarUtil.setStatusBarColor(this,R.color.white);
        }
    }

    private void initPermission(){
        permissionList = new ArrayList<>();
        permissionList.add(Manifest.permission.READ_PHONE_STATE);
        permissionList.add(Manifest.permission.INTERNET);
        permissionList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permissionList.add(Manifest.permission.CALL_PHONE);
        permissionList.add(Manifest.permission.CAMERA);
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        permissionList.add(Manifest.permission.CHANGE_WIFI_STATE);
        requestPermission(permissionList.toArray(new String[permissionList.size()]),REQUEST_CODE_PERMISSION);
    }
    /**
     * 转到登录页面
     * @param activityMob
     */
    public void turnToLoginActivity(BaseActivityMob_lib activityMob){
        Intent intent = new Intent(activityMob, LoginBaseActivity_lib.class);
        startActivity(intent);
        finish();
    }

    /**
     * 本地存值
     *
     * @param key
     * @param value
     */
    public static void writeLocationFile(String key, String value) {

        SharedPreferences.Editor edit = mShare.edit();
        edit.putString(key, value);
        edit.commit();

    }

    /**
     * 本地存值-object
     *
     * @param key
     * @param object
     */
    public static void writeLocationObject(String key, Object object) {

        MobUtils.writeObject(mShare, key, object);
    }

    /**
     * 是否等于或者超过7.0
     * @return
     */
    public static boolean isSurpass7Version(){

        if (Build.VERSION.SDK_INT >= 24) {
            return  true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            return true;
        }
        return false;
    }

    private void initManager() {
        // 初始化DBManager
        mgr = new DBManager(this);
    }

    /**
     * 功能: toast 封装
     *
     * @作者 zhangg
     */
    public Toast showMessageNotShow(Object text) {
        return Toast.makeText(getApplicationContext(), text + "",
                Toast.LENGTH_SHORT);
    }


    public BitmapUtils getBitmapUtils() {
        if (bitmapUtils == null) {
            bitmapUtils = new BitmapUtils(this); // 初始化BitmapUtils对象;
        }
        return bitmapUtils;
    }


    /**
     * 安全请求-防止截屏等功能
     */
    public void secureRequest() {
        // 安全
        mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }


    /**
     * 设置输入法默认不弹起
     */
    public void  setSoftInputHidden(){
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }


    /**
     * 为变量赋值
     */
    public void assignmentForParameter() {

        // 赋值
        mShare = getSharedPreferences(Constant.shared, MODE_PRIVATE);

        // 赋值
//        mShare = getSharedPreferences(Constant.shared, MODE_WORLD_WRITEABLE);
        bitmapUtils = new BitmapUtils(this); // 初始化BitmapUtils对象
        mActivity = this;
        appDownloadPath = mActivity.getApplicationContext().getFilesDir().getAbsolutePath() + "/";
        fragmentManager = getSupportFragmentManager();
        beginTransaction = fragmentManager.beginTransaction();
        initManager();

    }


    public SharedPreferences getmShare(){
        return mShare;
    }

    /**
     * 初始化view
     */
    public abstract void initView();

    /**
     * 初始化监听
     */
    public abstract void initListener();

    /**
     * 初始化数据
     */
    public abstract void initData();

    @Override
    public void onClick(View v) {

    }


    /***
     * 获取登录用户信息
     *
     * @return
     */
    public UserInfo_lib getUserInfo() {
        return readLocationObject(Constant.userInfo, UserInfo_lib.class);
    }
    /***
     * 获取登录用户信息
     *
     * @return
     */
    public UserInfoLRY getUserInfoLRY() {
        return readLocationObject(Constant.userInfoLry, UserInfoLRY.class);
    }

    /***
     * 获取登录用户信息
     *
     * @return
     */
    public UserInfo_lib getUserInfo_ma() {
        return readLocationObject(Constant.userInfo_ma, UserInfo_lib.class);
    }


    public void showToast(Object obj){

        if (mToast != null){
            mToast.cancel();
        }
        mToast = Toast.makeText(getApplicationContext(),obj+"",Toast.LENGTH_SHORT);
        mToast.show();




    }

    /**
     * 功能:导航栏的初始化工作
     *
     * @作者 zhangg
     */
    protected void initActionbar() {

//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        // 隐藏软键盘
//        getWindow().setSoftInputMode(
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);


    }


    /**
     * 功能: toast 封装
     *
     * @作者 zhangg
     */
    public void showMessage(Object text) {
        showToast(text);
    }


//    /**
//     * 本地取值
//     *
//     * @param key
//     * @return
//     */
//    public static String readLocationValue(String key) {
//        String value = mShare.getString(key, "");
//        return value;
//    }

    /**
     * 本地取值
     *
     * @param key
     * @return
     */
    public static String readLocationValue(String key) {
        String value = mShare.getString(key, "");
        return value;
    }

    /**
     * 本地取值
     *
     * @param key
     * @return
     */
    public static <T> T  readLocationObject(String key,Class classs) {
        T t = null;
        t = (T) MobUtils.readObject(mShare, key, classs);
        return t;
    }

//    /**
//     * 本地存值
//     *
//     * @param key
//     * @param value
//     */
//    public static void writeLocationFile(String key, String value) {
//        SharedPreferences.Editor edit = mShare.edit();
//        edit.putString(key, value);
//        edit.commit();
//    }

    /**
     * 清空本地值
     *
     * @param key
     */
    public static void clearLocationFile(String key) {
        SharedPreferences.Editor edit = mShare.edit();
        edit.remove(key);
        edit.commit();
    }



    /**
     * 判空(严格)
     *
     * @param obj
     * @return
     */
    public boolean isNull(Object obj) {
        return null == obj || "null".equals(obj)
                || "".equals(obj.toString().trim());
    }

    /**
     * 获取版本name
     *
     * @return 当前应用的版本name
     */
    public String getVersionName() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            showMessage(e.getMessage());
            LogUtils.e(e);
        }
        return "";
    }


    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public int getVersionCode() {

        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            int version = info.versionCode;
            return version;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return -1;
    }



    /**
     * 根据base64编码后的data，展示在webview上
     * @param webView
     * @param data
     */
    public void  showDataForWebview(Activity activity, WebView webView, String data){

        if (TextUtils.isEmpty(data)){
            Toast.makeText(activity,"数据为空",Toast.LENGTH_SHORT).show();
            return;
        }
        WebSettings webSettings = webView.getSettings();
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
        //webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//关闭硬件加速 ，一般不设置

        byte[] decodedata = Base64.decode(data,0);
        webView.loadDataWithBaseURL(null, new String(decodedata), "text/html", "utf-8", null);

    }



    /**
     * 输出error类型的日志
     * @param object
     */
    public static void LogError(Object object) {
        LogUtils.e(object);
    }




    /**
     * 宽松的校验(非严格)
     */
    public boolean isNullForLoose(Object obj) {
        if (null == obj || "null".equals(obj)
                || "".equals(obj.toString().trim())) {
            return true;
        }
        String tempString = obj.toString().trim();
        return "[]".equals(tempString) || "{}".equals(tempString);
    }


    /**
     * 获得当前时间
     * @return
     */
    public String getCurrentDate() {
        // SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormater = new SimpleDateFormat(
                "yyyy-MM-dd HHmmss");
        Date date = new Date();
        // System.out.print();?
        return dateFormater.format(date);
    }



    /******************  动态权限  开始  ******************************/


    /**
     * 是否等于或者超过6.0
     * @return
     */
    public boolean isSurpass6Version(){

        if (Build.VERSION.SDK_INT >= 23) {
            return  true;
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            return true;
        }
        return false;
    }

    //checkPermissions 检查
    // permissionSuccess 成功是走的,permissionFail失败时候走的

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    private boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    public List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<String>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }



    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }



    public  int REQUEST_CODE_PERMISSION = 1000;  // 默认的请求权限标示

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }


    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        LogUtils.e("获取权限成功=" + requestCode);

    }

    /**
     * 权限获取失败
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        LogUtils.e("获取权限失败=" + requestCode);
    }


    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }


    /******************  动态权限  结束  ******************************/


    /******************  沉侵式状态了 start ******************************/

    /**
     * (系统实现)沉浸式状态栏 实现方式一
     */
    private void initStateForOS() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }



    /**
     * 动态的设置状态栏  实现沉浸式状态栏 实现方式二
     * @parameter topLayout  顶部状态栏(要使用这个方法必须实现topLayout的值)
     */
    private void initStateForDynamic(LinearLayout topLayout) {

        //当系统版本为4.4或者4.4以上时可以使用沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            //
            LinearLayout linear_bar = topLayout;//实际使用要替换
            linear_bar.setVisibility(View.VISIBLE);
            //获取到状态栏的高度
            int statusHeight = getStatusBarHeight();
            //动态的设置隐藏布局的高度
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear_bar.getLayoutParams();
            params.height = statusHeight;
            linear_bar.setLayoutParams(params);
        }
    }

    /**
     * 通过反射的方式获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /******************  沉侵式状态了 end ******************************/


    /******************  callServiceEx start ******************************/

    /**
     * 调用后台
     * @param mActivity
     * @param json
     * @param callback
     */
    public void callServiceEx(BaseActivityMob_lib mActivity, JSONObject json, ServiceCallback callback){

        try {
            MAServices_lib.callMACommonService(mActivity, callback,json);
        } catch (Exception e) {
            LogUtils.e(e);
            if (mActivity!=null){
                mActivity.showToast(e);
            }
            e.printStackTrace();
        }
    }


    // 递归方式 计算文件的大小
    public long getTotalSizeOfFilesInDir(final File file) {
        if (file.isFile())
            return file.length();
        final File[] children = file.listFiles();
        long total = 0;
        if (children != null)
            for (final File child : children)
                total += getTotalSizeOfFilesInDir(child);
        return total;
    }


    /**
     * 调用后台回调
     */
    public abstract class CallBack implements ServiceCallback{
        @Override
        public void execute(JSONObject jsonObject) {
            executeSuccess(jsonObject);
        }

        @Override
        public void error(String s, String s1) {
            executeFailure(s,s1);
        }

        public abstract void executeSuccess(JSONObject jsonObject);
        public abstract void executeFailure(String s, String s1);

    }


    /******************  callServiceEx end ******************************/



}
